//
//  RechargeViewController.m
//  penzer
//
//  Created by caiyc on 2018/9/21.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "RechargeViewController.h"
#import "WXApi.h"
#import "PackageView.h"
#import "RechargeSuccessViewController.h"
#import "DXAlertView.h"
@interface RechargeViewController ()<UIScrollViewDelegate,DXAlertViewDelegate,UITextFieldDelegate>
{
    BOOL isHaveDian;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *topV;
@property (weak, nonatomic) IBOutlet UIView *bottomV;
@property (weak, nonatomic) IBOutlet UIView *titleV;
@property (weak, nonatomic) IBOutlet UILabel *count;
@property (weak, nonatomic) IBOutlet UITextField *tf;
@property (weak, nonatomic) IBOutlet UIButton *rechargeBtn;
@property (weak, nonatomic) IBOutlet UILabel *line;
@property (nonatomic,strong) NSMutableArray<PackageView *> *packages;
@property(nonatomic,strong)PackageView *selectView;
@property(nonatomic,strong)NSString*snpackageid;
@property(nonatomic,strong)NSString *price;
@property(nonatomic,strong)NSString *order_id;

@end

@implementation RechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigation:1 andTitle:@"充值中心" andNaviColor:nil andTitleColor:nil];
    self.snpackageid = @"";
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
    [self.view addGestureRecognizer:tap];
    self.topV.backgroundColor = [UIColor whiteColor];
    self.titleV.backgroundColor = [UIColor whiteColor];
    self.bottomV.backgroundColor = [UIColor whiteColor];
    self.rechargeBtn.layer.cornerRadius = 5;
    self.line.layer.cornerRadius = 2;
    self.tf.delegate = self;
    [self.tf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self setAttrbuteText:@"0次机会"];
    [self fetchPackage];
  //  [self setupPackge];
}
-(void)setAttrbuteText:(NSString *)str{
    NSString *price_text = [str substringWithRange:NSMakeRange(0, str.length-3)];
    NSDictionary *attrDict1 = @{NSFontAttributeName:[UIFont fontWithName: @"Helvetica-Bold" size: 74]
                                 };
    NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString: price_text attributes: attrDict1];
    
    NSString *price_text1 =  [str substringWithRange:NSMakeRange(str.length-3, 3)];;
    NSDictionary *attrDict2 = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    NSAttributedString *attrStr3 = [[NSAttributedString alloc] initWithString: price_text1 attributes: attrDict2];
    NSMutableAttributedString *strs = [[NSMutableAttributedString alloc]init];
    [strs appendAttributedString:attrStr1];
    [strs appendAttributedString:attrStr3];
    self.count.attributedText = strs;
}

-(void)textFieldDidChange:(UITextField *)textField{
    self.snpackageid = @"";
    if(textField==self.tf){
        if(textField.text.length>0){
        [self setAttrbuteText:[NSString stringWithFormat:@"%@次机会",textField.text]];
        self.price = textField.text;
        }else{
            [self setAttrbuteText:@"0次机会"];
            self.price = @"";
        }
        
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    
    if ([textField.text rangeOfString:@"."].location == NSNotFound)
    {
        isHaveDian = NO;
    }
    if ([string length] > 0)
    {
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([textField.text length] == 0)
            {
                
                if(single == '.')
                {
                    
                  //  [self showMyMessage:@"亲，第一个数字不能为小数点!"];
                    
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    
                    return NO;
                    
                }
                
                if (single == '0')
                {
                    
                  //  [self showMyMessage:@"亲，第一个数字不能为0!"];
                    
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    
                    return NO;
                    
                }
                
            }
            
            //输入的字符是否是小数点
            
            if (single == '.')
            {
                
                if(!isHaveDian)//text中还没有小数点
                {
                    
                    isHaveDian = YES;
                    
                    return YES;
                    
                }else{
                    
                //    [self showMyMessage:@"亲，您已经输入过小数点了!"];
                    
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    
                    return NO;
                    
                }
                
            }else{
                
                if (isHaveDian) {//存在小数点
                    
                    //判断小数点的位数
                    
                    NSRange ran = [textField.text rangeOfString:@"."];
                    
                    if (range.location - ran.location <= 2) {
                        
                        return YES;
                        
                    }else{
                        
                     //   [self showMyMessage:@"亲，您最多输入两位小数!"];
                        
                        return NO;
                        
                    }
                    
                }else{
                    
                    return YES;
                    
                }
                
            }
            
        }else{//输入的数据格式不正确
            
           // [self showMyMessage:@"亲，您输入的格式不正确!"];
            
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            
            return NO;
            
        }
        
    }
    
    else
        
    {
        
        return YES;
        
    }
    
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self setupPackgeViewFrame];
}


-(void)hideKb{
    [self.view endEditing:1];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:1];
}



- (IBAction)shuoming {
}

- (IBAction)recharge {
    [self.view endEditing:1];
    if(self.tf.text.length==0){
        return;
    }else{
        [self buyAction];
    }
//    RechargeSuccessViewController *vc = [RechargeSuccessViewController new];
//    [self presentViewController:vc animated:YES completion:nil];
}


#pragma mark--获取套餐
- (void)fetchPackage
{
    /**
     http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=store&op=activity&m=bz_activities&token=8175f62516aae4aa5e9ff6fc81b44112&ta=snpackage_list&type=1
     **/
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"snpackage_list",@"type":@"1"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            NSArray *data = response[@"data"];
            if(data.count==0){
                [WToast showWithText:@"暂无套餐数据"];
            }else{
                for(int i =0;i<data.count;i++){
                    PackageView *view = [PackageView new];
                    [view bindData:data[i]];
                    view.imageV.image = [UIImage imageNamed:@"icon_cz_nomal"];
                    view.tag = index;
                    
                    view.onClickBlock = ^(PackageView *view) {
                        view.btn.selected = !view.btn.selected;
                        if(view.btn.selected==1){
                            //弹出充值提示框
                            self.price = view.price;
                            self.snpackageid = view.snpackageid;
                            NSString *strings = [NSString stringWithFormat:@"是否充值%@元，获得%@",view.label3.text,view.label2.text];
                            DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"充值提示" message:strings cancelBtnTitle:@"暂不充值" otherBtnTitle:@"充值"];
                            alert.delegate = self;
                            [alert show];
                        }
                        if(view==self.selectView){
                            if(view.btn.selected==1){
                                view.imageV.image = [UIImage imageNamed:@"icon_cz_selected"];
                            }else{
                                view.imageV.image = [UIImage imageNamed:@"icon_cz_nomal"];
                            }
                            
                        }else{
                            self.selectView.imageV.image =  [UIImage imageNamed:@"icon_cz_nomal"];
                            view.imageV.image = [UIImage imageNamed:@"icon_cz_selected"];
                            self.selectView = view;
                            }
                    };
                    [self.bottomV addSubview:view];
                    [self.packages addObject:view];
                }
            }
        }
    } failure:^(NSError *error) {
        
    }];
//    HelenParametersDic *dict = [HelenParametersDic h_dictionary];
//    /**
//     http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=member&op=task&m=bz_activities&token=87ffec5d746e139250f2da176caff727&ta=index
//
//     category 任务分类
//     */
//    dict[@"ctrl"] = @"live";
//    dict[@"ac"] = @"member";
//    dict[@"op"] = @"task";
//    dict[@"token"] = [RZ_USERDEFAULTES objectForKey:USER_INFO][@"token"];
//
//    [HelenHttpClient requestWithUrlString:BASE_URL andParam:dict andMethod:@"POST" progress:nil success:^(id responseObject) {
//
//        NSDictionary *res = responseObject[@"message"];
//        NSInteger code = [res[@"resultCode"] integerValue];
//        if(code== 0 || code ==1){
//
//        }
//
//    } andFailBlock:^(NSInteger ErrorCode, NSError *ErrorString) {
//
//    }];
}


-(void)dxAlertView:(DXAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex!=0){
        //确认充值
        [self buyAction];
    }
}
-(void)buyAction{
    /**
     http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=store&op=activity&m=bz_activities&token=8175f62516aae4aa5e9ff6fc81b44112&ta=snpackage_order
     **/
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"snpackage_order",@"price":self.price,@"snpackageid":self.snpackageid};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            self.order_id = [NSString stringWithFormat:@"%@",response[@"data"]];
            [self next];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)setupPackge
{

//    for (NSInteger index = 0; index < 4; index++) {
//        PackageView *view = [PackageView new];
//        [self.bottomV addSubview:view];
//        [self.packages addObject:view];
//    }


    for (NSInteger index = 0; index < 4; index++) {
        PackageView *view = [PackageView new];
        view.imageV.image = [UIImage imageNamed:@"icon_cz_nomal"];
        view.tag = index;
        view.onClickBlock = ^(PackageView *view) {
            view.btn.selected = !view.btn.selected;
            if(view==self.selectView){
                if(view.btn.selected==1){
                    view.imageV.image = [UIImage imageNamed:@"icon_cz_selected"];
                }else{
                    view.imageV.image = [UIImage imageNamed:@"icon_cz_nomal"];
                }
                
            }else{
            self.selectView.imageV.image =  [UIImage imageNamed:@"icon_cz_nomal"];
            view.imageV.image = [UIImage imageNamed:@"icon_cz_selected"];
            self.selectView = view;
              
            }
        };
        [self.bottomV addSubview:view];
        [self.packages addObject:view];
    }
    

}


-(void)setupFooterView{
    
}
- (void)setupPackgeViewFrame
{
    CGSize size_image = [UIImage imageNamed:@"icon_cz_nomal"].size;
    NSInteger maxCount = 2;
    CGFloat margin_x = 20;
    CGFloat margin_y = 20;
    CGFloat w = (self.bottomV.width - (maxCount+1)*margin_x) / maxCount;
//    CGFloat h = w /(size_image.width / size_image.height);
    CGFloat h = size_image.height;
    [self.packages enumerateObjectsUsingBlock:^(PackageView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSInteger row = idx / maxCount;
        NSInteger col = idx % maxCount;
        CGFloat x = margin_x + (margin_x+w)*col;
        CGFloat y = margin_y + (margin_y+h)*row;
        view.frame = CGRectMake(x, y, w, h);
    }];
    
    self.bottomV.height = CGRectGetMaxX(self.packages.lastObject.frame);
    CGSize size = self.scrollView.contentSize;
    size.height = CGRectGetMaxY(self.topV.frame)+self.bottomV.height+30;
    self.scrollView.contentSize = size;
}


- (void)next{
   // [WToast showWithText:@"等待商家接入账号"];
    NSDictionary *param = @{@"i":@"10",@"m":@"bz_activities",@"c":@"entry",@""@"id":self.order_id,@"op":@"pay",@"ac":@"system",@"ctrl":@"live",@"token":[XTool GetDefaultInfo:USER_INFO][@"token"],@"pay_type":@"act_morenum"};
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    
    [manager POST:BASE_URL parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        if([responseObject[@"message"][@"errno"]integerValue]==0){
            PayReq* req             = [[PayReq alloc] init];
            // req.
            req.partnerId           = @"1515323121";
            
            req.prepayId            = responseObject[@"message"][@"message"][@"prepayid"];
            //  req.nonceStr            = [self createnonceStr];
            req.nonceStr            = responseObject[@"message"][@"message"][@"noncestr"];
            req.timeStamp = [responseObject[@"message"][@"message"][@"timestamp"]intValue];
            req.package             = @"Sign=WXPay";
            req.sign                = responseObject[@"message"][@"message"][@"sign"];
            [WXApi sendReq:req];
        }else{
            [WToast showWithText:@"请求出错"];
        }
        
        
        
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}



#pragma mark--getter&&setter
-(NSMutableArray<PackageView *> *)packages
{
    if(!_packages){
        _packages = [NSMutableArray array];
    }
    return _packages;
}

@end
